package com.hong.controller.system;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hong.common.AjaxResultVo;
import com.hong.common.anno.Log;
import com.hong.common.controller.BaseController;
import com.hong.common.shiro.AuthorizationUtils;
import com.hong.entity.SysRole;
import com.hong.entity.SysRoleMenu;
import com.hong.entity.SysUser;
import com.hong.entity.SysUserRole;
import com.hong.entity.vo.TreeMenuAllowAccess;
import com.hong.service.ISysMenuService;
import com.hong.service.ISysRoleMenuService;
import com.hong.service.ISysRoleService;
import com.hong.service.ISysUserRoleService;
import com.hong.service.ISysUserService;

@Controller
@RequestMapping("/system/role")
public class RoleController extends BaseController {

	@Autowired
	private ISysRoleService sysRoleService;

	@Autowired
	private ISysUserRoleService sysUserRoleService;

	@Autowired
	private ISysUserService sysUserService;

	@Autowired
	private ISysMenuService sysMenuService;

	@Autowired
	private ISysRoleMenuService sysRoleMenuService;

	/**
	 * 跳转角色管理
	 * 
	 * @return
	 */
	@RequiresPermissions("listRole")
	@RequestMapping("/listPage")
	public String listPage() {
		return "system/role/list";
	}

	/**
	 * 分页查询角色
	 * 
	 * @param search
	 * @param daterange
	 * @param limit
	 * @param offset
	 * @return
	 */
	@RequiresPermissions("listRole")
	@RequestMapping("/listRole")
	@ResponseBody
	public AjaxResultVo listRole(String search, String daterange, Integer limit, Integer offset) {
		QueryWrapper<SysRole> ew = new QueryWrapper<SysRole>();
		if (StringUtils.isNotBlank(search)) {
			ew.like("role_name", search);
		}
		ew.orderByAsc("create_time");
		PageHelper.startPage(getPageNo(limit, offset), limit);
		List<SysRole> roleList = sysRoleService.list(ew);
		PageInfo<SysRole> pageData = new PageInfo<>(roleList);
		AjaxResultVo resultVo = AjaxResultVo.success();
		resultVo.put("total", pageData.getTotal());
		resultVo.put("rows", pageData.getList());
		return resultVo;
	}

	/**
	 * 跳转创建角色
	 * 
	 * @return
	 */
	@RequiresPermissions("addRole")
	@RequestMapping("/add")
	public String add() {
		return "system/role/add";
	}

	/**
	 * 执行新增角色
	 * 
	 * @param role
	 * @return
	 */
	@Log("创建角色")
	@RequiresPermissions("addRole")
	@RequestMapping("/doAdd")
	@ResponseBody
	public AjaxResultVo doAdd(SysRole role) {
		role.setCreateTime(new Date());
		sysRoleService.save(role);
		AuthorizationUtils.clearAllCachedAuthorizationInfo();
		return AjaxResultVo.success();

	}

	/**
	 * 编辑角色
	 * 
	 * @param id
	 * @return
	 */
	@RequiresPermissions("editRole")
	@RequestMapping("/edit/{id}")
	public String edit(@PathVariable String id, Model model) {
		SysRole sysRole = sysRoleService.getById(id);
		model.addAttribute(sysRole);
		return "system/role/edit";
	}

	/**
	 * 执行编辑角色
	 * 
	 * @param sysRole
	 * @return
	 */
	@Log("编辑角色")
	@RequiresPermissions("editRole")
	@RequestMapping("/doEdit")
	@ResponseBody
	public AjaxResultVo doEdit(SysRole sysRole) {
		sysRoleService.updateById(sysRole);
		AuthorizationUtils.clearAllCachedAuthorizationInfo();
		return AjaxResultVo.success();
	}

	/**
	 * 跳转授权页面
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequiresPermissions("authRole")
	@RequestMapping("/auth/{id}")
	public String auth(@PathVariable String id, Model model) {
		SysRole sysRole = sysRoleService.getById(id);
		if (sysRole == null) {
			throw new RuntimeException("该角色不存在");
		}
		List<SysRoleMenu> sysRoleMenus = sysRoleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id", id));
		List<String> menuIds = sysRoleMenus.stream().map(m -> m.getMenuId()).collect(Collectors.toList());
		List<TreeMenuAllowAccess> treeMenuAllowAccesses = sysMenuService
				.selectTreeMenuAllowAccessByMenuIdsAndPid(menuIds, "0");
		model.addAttribute("sysRole", sysRole);
		model.addAttribute("treeMenuAllowAccesses", treeMenuAllowAccesses);
		return "system/role/auth";
	}

	/**
	 * 执行角色授权
	 * 
	 * @param roleId
	 * @param mid
	 * @return
	 */
	@Log("角色分配权限")
	@RequiresPermissions("authRole")
	@RequestMapping("/doAuth")
	@ResponseBody
	public AjaxResultVo doAuth(String roleId, @RequestParam(value = "mid[]", required = false) String[] mid) {
		sysRoleMenuService.addAuth(roleId, mid);
		return AjaxResultVo.success("OK,授权成功!");
	}

	/**
	 * 删除角色
	 * 
	 * @param id
	 * @return
	 */
	@Log("删除角色")
	@RequiresPermissions("deleteRole")
	@RequestMapping("/delete/{id}")
	@ResponseBody
	public AjaxResultVo delete(@PathVariable String id) {
		if (StringUtils.isBlank(id)) {
			return AjaxResultVo.error("参数错误");
		}
		List<String> ids = new ArrayList<String>(1);
		ids.add(id);
		if (sysRoleService.deleteByIds(ids)) {
			return AjaxResultVo.success();
		} else {
			return AjaxResultVo.error("删除失败");
		}
	}

	/**
	 * 批量删除角色
	 * 
	 * @param ids
	 * @return
	 */
	@Log("批量删除角色")
	@RequiresPermissions("deleteRole")
	@RequestMapping("/deleteBatch")
	@ResponseBody
	public AjaxResultVo deleteBatch(@RequestParam("id[]") List<String> ids) {
		if (ObjectUtils.isEmpty(ids)) {
			return AjaxResultVo.error("参数错误");
		}
		if (sysRoleService.deleteByIds(ids)) {
			return AjaxResultVo.success();
		} else {
			return AjaxResultVo.error("删除失败");
		}
	}

	/**
	 * 获取角色下的所有授权用户
	 * 
	 * @param roleId
	 * @param model
	 * @return
	 */
	@RequestMapping("/getUsersByRoleId/{roleId}")
	public String getUsersByRoleId(@PathVariable String roleId, Model model) {
		QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
		queryWrapper.eq("role_id", roleId);
		List<SysUserRole> sysUserRoles = sysUserRoleService.list(queryWrapper);
		List<String> userIds = sysUserRoles.stream().map(m -> m.getUserId()).collect(Collectors.toList());
		List<SysUser> users = new ArrayList<SysUser>();
		if (userIds.size() > 0) {
			QueryWrapper<SysUser> ew = new QueryWrapper<SysUser>();
			ew.in("id", userIds);
			users = sysUserService.list(ew);
		}
		model.addAttribute("users", users);
		return "system/role/users";
	}

}
